package com.kha.listone.util.xml;

import java.io.IOException;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import org.kxml2.io.KXmlSerializer;
import org.kxml2.kdom.Document;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;

import com.kha.listone.util.Globals;
import com.kha.listone.util.operation.Operation;

public class SettingsXMLGenerator implements Operation {

	public SettingsXMLGenerator() {
		super();
	}

	public void createDocument() {

		if (Globals.settingListOne != null) {

			try {
				FileConnection fileConn = (FileConnection) Connector.open(
						Globals.XML_SETTINGS_FILE_PATH, Connector.READ_WRITE);
				if (fileConn.exists()) {
					fileConn.delete();
				}
				fileConn.create();
				OutputStream outStream = fileConn.openOutputStream();

				// Create the new xml file for
				Document doc = new Document();

				Element root = doc.createElement("", "parent");
				root.setName(Globals.TAG_SETTINGS);

				Element dateFormat = doc.createElement("", "child");
				dateFormat.setName(Globals.TAG_SETTING_DATEFORMAT);
				dateFormat.addChild(0, Node.TEXT,
						String.valueOf(Globals.settingListOne.getDateFormat()));

				Element language = doc.createElement("", "child");
				language.setName(Globals.TAG_SETTING_LANGUAGE);
				language.addChild(0, Node.TEXT,
						String.valueOf(Globals.settingListOne.getLanguage()));

				Element syncTime = doc.createElement("", "child");
				syncTime.setName(Globals.TAG_SETTING_SYNCTIME);
				syncTime.addChild(0, Node.TEXT,
						String.valueOf(Globals.settingListOne.getSyncTime()));

				Element haveDropbox = doc.createElement("", "child");
				haveDropbox.setName(Globals.TAG_HAVE_DROPBOX);
				haveDropbox.addChild(0, Node.TEXT,
						String.valueOf(Globals.HAVE_DROPBOX ? 1 : 0));

				Element userDropbox = doc.createElement("", "child");
				userDropbox.setName(Globals.TAG_DROPBOX_USERNAME);
				userDropbox.addChild(0, Node.TEXT, Globals.DROPBOX_USERNAME);

				Element passDropbox = doc.createElement("", "child");
				passDropbox.setName(Globals.TAG_DROPBOX_PASSWORD);
				passDropbox.addChild(0, Node.TEXT, Globals.DROPBOX_PASSWORD);

				root.addChild(0, Node.ELEMENT, dateFormat);
				root.addChild(0, Node.ELEMENT, language);
				root.addChild(0, Node.ELEMENT, syncTime);
				root.addChild(0, Node.ELEMENT, haveDropbox);
				root.addChild(0, Node.ELEMENT, userDropbox);
				root.addChild(0, Node.ELEMENT, passDropbox);

				doc.addChild(0, Node.ELEMENT, root);

				// Write into the serialization
				KXmlSerializer serializer = new KXmlSerializer();
				serializer.setOutput(outStream, "UTF-8");

				doc.write(serializer);
				outStream.close();
				fileConn.close();				

			} catch (IOException e) {

				e.printStackTrace();
			}
		}
	}

	public void execute() {
		this.createDocument();
	}

}
